
//
//  ZFBCycleView.m
//  02-图片无线轮播
//
//  Created by jieChen on 17/1/17.
//  Copyright © 2017年 jieChen. All rights reserved.
//

#import "ZFBCycleView.h"
#import "ZFBCycleFlowLayout.h"
#import <Masonry.h>
#import "ZFBCycleCell.h"
@interface ZFBCycleView ()<UICollectionViewDataSource,UICollectionViewDelegate>


@property (nonatomic,weak)UICollectionView *collectionView;

@property (nonatomic,weak)UIPageControl *pageControl;

@property (nonatomic,strong)NSTimer *timer;

@end


// 组数
#define ZFBCycleSectionCount 3
static NSString *ZFBCycleCellID = @"ZFBCycleCellID";
@implementation ZFBCycleView
// 如果当前类通过 xib sb方式创建 调用此方法
- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setupUI];
}
// 如果当前类通过代码创建,调用此方法
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    // 2.设置collectionView
    [self settingCollectionView];
    
    // 第一个参数表示间隔时间
    // 第二个参数表示给谁添加一个定时器
    // 第三个参数表示要执行的方法
    // 第四个参数表示额外信息
    // 第五个参数表示是否重复执行这个定时器的事情
    _timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextPath) userInfo:nil repeats:YES];
    
    // 把定时器添加到运行循坏并且指定为通用模式
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
    
    // 3.添加分页指示器
    UIPageControl *pageControl = [[UIPageControl alloc]init];
    pageControl.currentPageIndicatorTintColor = [UIColor colorWithWhite:0.6 alpha:1];
    pageControl.pageIndicatorTintColor = [UIColor colorWithWhite:0.9 alpha:1];
    // 分页指示器根据图片的数据改变
    pageControl.numberOfPages = self.imageNames.count;
    [self addSubview:pageControl];
    
    // 添加约束
    [pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.bottom.offset(0);
    }];
    
    _pageControl = pageControl;
}


#pragma mark - 定时器每两秒要做的方法
- (void)nextPath
{
    // 1.获取当前滚动到第几页
    NSInteger page = self.pageControl.currentPage;
    
    NSIndexPath *scrollToPath;
    
    // 如果在最后一页回到第0页
    if (page == self.imageNames.count - 1) {
        // 如果滚动到中间这一组的第最后一页 怎么办
        scrollToPath = [NSIndexPath indexPathForItem:0 inSection:ZFBCycleSectionCount / 2 + 1];
        
    }else{ // 如果不是最后一页就到下一页
        // 如果不是在中间组的最后一页继续向下一页滚动
        scrollToPath = [NSIndexPath indexPathForItem:page + 1 inSection:ZFBCycleSectionCount / 2];
    }
    
    
    // 5.让collectionView回滚到中间组的第item的cell上
    [self.collectionView scrollToItemAtIndexPath:scrollToPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

- (void)settingCollectionView 
{
    // 0.创建流布局对象
    ZFBCycleFlowLayout *cycleFlaowLayout = [[ZFBCycleFlowLayout alloc]init];
    // 1.创建collectionView对象
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:cycleFlaowLayout];
    
    collectionView.backgroundColor = [UIColor whiteColor];
    
    [self addSubview:collectionView];
    
    // 2.添加约束
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    
    // 3.设置数据源
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    // 4.注册
    UINib *nib = [UINib nibWithNibName:@"ZFBCycleCell" bundle:nil];
    [collectionView registerNib:nib forCellWithReuseIdentifier:ZFBCycleCellID];
    
    _collectionView = collectionView;
    
#pragma mark - 封装后不要用
//    [self layoutIfNeeded];
//    
//    // 要滚到的索引
//    NSIndexPath *scrollToPath = [NSIndexPath indexPathForItem:0 inSection:ZFBCycleSectionCount / 2];
//    
//    // 5.让collectionView默认显示中间这一组的第0个cell
//    [collectionView scrollToItemAtIndexPath:scrollToPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

#pragma mark - 重写数据属性的set方法,当有了数据以后再去默认滚动到中间哪一组的第0行
- (void)setImageNames:(NSArray *)imageNames
{
    _imageNames = imageNames;
    
    _pageControl.numberOfPages = self.imageNames.count;
    [self layoutIfNeeded];
     //要滚到的索引
    NSIndexPath *scrollToPath = [NSIndexPath indexPathForItem:0 inSection:ZFBCycleSectionCount / 2];
    
    // 5.让collectionView默认显示中间这一组的第0个cell
    [self.collectionView scrollToItemAtIndexPath:scrollToPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
}

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    // 要滚到的索引
//    NSIndexPath *scrollToPath = [NSIndexPath indexPathForItem:0 inSection:ZFBCycleSectionCount / 2];
//    
//    // 5.让collectionView默认显示中间这一组的第0个cell
//    [self.collectionView scrollToItemAtIndexPath:scrollToPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

#pragma mark - 用代码的方式去滚动,滚动完一页停下来之后此方法会调用一次
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self scrollViewDidEndDecelerating:scrollView];
}

#pragma  mark - 此方法只有手动拖拽时当cell完全挺下来才会调一次
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x / scrollView.bounds.size.width;
    // 当前界面上的这个CELL的组的索引
    NSInteger section = page / self.imageNames.count;
    // 当前界面上的cell的组的item索引
    NSInteger item = page % self.imageNames.count;
    
    _pageControl.currentPage = page % self.imageNames.count;
    
    // 如果当前还在中间那组,就什么也不做
    if (section == ZFBCycleSectionCount / 2){
        return;
    }
    
    
    // 滚动到索引
    NSIndexPath *scrollToPath = [NSIndexPath indexPathForItem:item inSection:ZFBCycleSectionCount / 2];
    
    // 5.让collectionView回滚到中间组的第item的cell上
    [self.collectionView scrollToItemAtIndexPath:scrollToPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
        NSInteger page = scrollView.contentOffset.x / scrollView.bounds.size.width / 0.4999;
    
        // 设置当前页
        _pageControl.currentPage = page % self.imageNames.count;
}


#pragma mark - 将要开始拖拽时调用一次
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 设置定时器开始执行的时间
    // 让它在未来的某个时间再去执行"假暂停"
    _timer.fireDate = [NSDate distantFuture];
}

#pragma mark - 当用户松开手之后让定时器重新执行
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    // 让定时器在2秒后开始执行
    _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2.0];
}


#pragma mark - 数据源方法
// 返回组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return ZFBCycleSectionCount;
}
// 返回行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageNames.count;
}

// 返回cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
    ZFBCycleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZFBCycleCellID forIndexPath:indexPath];
    
    // 2.设置cell
    
    cell.indexPath = indexPath;
    // 3.返回cell
    return cell;
}

#pragma mark - 当一个控件要从它的父控制上移除时就调用此方法,但是调用此方法不代表控件就要销毁了
- (void)removeFromSuperview{
    [super removeFromSuperview];
    // 停止定时器,解除引用
    [_timer invalidate];
}
@end
